package com.uhylab.uhuvinetest.activity;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.uhylab.uhuvinetest.R;
import com.uhylab.uhuvinetest.base.UHBase;
import com.uhylab.uhuvinetest.base.UHBaseActivity;
import com.uhylab.uhuvinetest.bean.StringData;
import com.uhylab.uhuvinetest.utils.VolleySingleton;
import com.uhylab.uhuvinetest.utils.sharedpreutils.SharedPreUtils;
import com.zhy.autolayout.AutoRelativeLayout;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;


/**
 * Created by xyb on 15/12/29 at UHylab
 *
 * @version 1.0
 */
public class UHLogonActivity extends UHBaseActivity implements CompoundButton.OnCheckedChangeListener, View.OnClickListener, PlatformActionListener {
    private static final int MSG_ACTION_CCALLBACK = 1;
    private static final int MSG_TOAST = 2;
    private static final int MSG_CANCEL_NOTIFY = 3;
    private EditText delEditText;
    private EditText editText;
    private AutoRelativeLayout loggon;
    private TextView registered;
    private TextView retrieve_password;
    private VolleySingleton volleySingleton;
    private String tel = "";//账号
    private String password = "";// 密码
    private ImageView register_back;
    private ImageView registered_wo;    //沃互联登录方式
    private ImageView registered_sina;  //通过新浪登录


    @Override
    public int bindLayout() {
        return R.layout.activity_logontwo;
    }

    @Override
    public void initView(View view) {
        volleySingleton = VolleySingleton.getVolleySingleton(getApplicationContext());
        delEditText = (EditText) view.findViewById(R.id.user_telphone);
        editText = (EditText) view.findViewById(R.id.user_password);
        loggon = (AutoRelativeLayout) view.findViewById(R.id.loggon);
        registered = (TextView) view.findViewById(R.id.registered);
        retrieve_password = (TextView) view.findViewById(R.id.retrieve_password);
        register_back = (ImageView) view.findViewById(R.id.register_back);
        registered_wo = (ImageView) findViewById(R.id.registered_wo);
        registered_sina = (ImageView) findViewById(R.id.registered_sina);

        Intent intent = getIntent();
        if (intent != null) {
            delEditText.setText(intent.getStringExtra("telephone"));
            editText.setText(intent.getStringExtra("password"));
        }
    }

    @Override
    public void doBusiness(Context mContext) {
        loggon.setOnClickListener(this);
        registered.setOnClickListener(this);
        retrieve_password.setOnClickListener(this);
        register_back.setOnClickListener(this);
        registered_wo.setOnClickListener(this);
        registered_sina.setOnClickListener(this);
    }

    @Override
    public void resume() {

    }


    @Override
    public void destroy() {
        volleySingleton.removeRequest("logon");
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loggon:
                loggin();
                break;
            case R.id.registered:
                // 注册页面
                Intent intent = new Intent(this, UHRegisteredActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.retrieve_password:
                // 找回密码页面
                Intent retrieve_password = new Intent(this, UHBackPasswordActivity.class);
                startActivity(retrieve_password);
                break;

            case R.id.register_back:
                // 返回上一页
                if (UHLogonActivity.this != null) {
                    finish();
                }
                break;
            case R.id.registered_wo:
                //通过沃互联进入
                Intent registeredWoIntent = new Intent(this, RegisteredWoActivity.class);
                startActivity(registeredWoIntent);
                break;
            case R.id.registered_sina:
                //通过新浪微博授权进入
                sinaLogin();
                break;
        }
    }

    //-----------------------------------------------------新浪微博授权相关--------------

    /**
     * 新浪微博授权、获取用户信息页面
     */
    private void sinaLogin() {
        ShareSDK.initSDK(getApplicationContext());


        //初始化新浪平台
        Platform pf = ShareSDK.getPlatform(UHLogonActivity.this, SinaWeibo.NAME);
//        pf.SSOSetting(true);
        pf.SSOSetting(false);
        //设置监听
        pf.setPlatformActionListener(this);
        //获取登陆用户的信息，如果没有授权，会先授权，然后获取用户信息

        pf.authorize();
    }

    /**
     * 新浪微博授权成功回调页面
     */
    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> hashMap) {
        /** res是返回的数据，例如showUser(null),返回用户信息，对其解析就行
         *   http://sharesdk.cn/androidDoc/cn/sharesdk/framework/PlatformActionListener.html
         *
         */
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 1;
        msg.arg2 = action;
        msg.obj = platform;
//        UIHandler.sendMessage(msg, this);
        handler.sendMessage(msg);
    }

    /**
     * 取消授权
     */
    @Override
    public void onCancel(Platform platform, int action) {
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 3;
        msg.arg2 = action;
        msg.obj = platform;
//        UIHandler.sendMessage(msg, this);
        handler.sendMessage(msg);
    }

    /**
     * 授权失败
     */
    @Override
    public void onError(Platform platform, int action, Throwable t) {
        t.printStackTrace();
        t.getMessage();
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 2;
        msg.arg2 = action;
        msg.obj = t;
//        UIHandler.sendMessage(msg, this);
        handler.sendMessage(msg);
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_TOAST: {
                    String text = String.valueOf(msg.obj);
                    //Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
                }
                break;
                case MSG_ACTION_CCALLBACK: {
                    switch (msg.arg1) {
                        case 1: {
                            // 成功, successful notification
                            //授权成功后,获取用户信息，要自己解析，看看oncomplete里面的注释
                            //ShareSDK只保存以下这几个通用值
                            Platform pf = ShareSDK.getPlatform(UHLogonActivity.this, SinaWeibo.NAME);

                            Log.e("sharesdk use_id", pf.getDb().getUserId()); //获取用户id
                            Log.e("sharesdk use_name", pf.getDb().getUserName());//获取用户名称
                            Log.e("sharesdk use_icon", pf.getDb().getUserIcon());//获取用户头像
                            // mThirdLoginResult.setText("授权成功"+"\n"+"用户id:" + pf.getDb().getUserId() + "\n" + "获取用户名称" + pf.getDb().getUserName() + "\n" + "获取用户头像" + pf.getDb().getUserIcon());
//                                  mPf = ShareSDK.getPlatform(MainActivity.this, SinaWeibo.NAME);
//                                  mPf.author();
                            //mPf.author()这个方法每一次都会调用授权，出现授权界面
                            //如果要删除授权信息，重新授权
                            //mPf.getDb().removeAccount();
                            //调用后，用户就得重新授权，否则下一次就不用授权

                            //获得用户id，用户名以及用户头像


                        }
                        break;
                        case 2: {
                            // mThirdLoginResult.setText("登录失败");
                        }
                        break;
                        case 3: {
                            // 取消, cancel notification
                            // mThirdLoginResult.setText("取消授权");
                        }
                        break;
                    }
                }
                break;
                case MSG_CANCEL_NOTIFY: {
                    NotificationManager nm = (NotificationManager) msg.obj;
                    if (nm != null) {
                        nm.cancel(msg.arg1);
                    }
                }
                break;
            }

        }
    };


    private void loggin() {
        tel = delEditText.getText().toString();
        password = editText.getText().toString();
        if (TextUtils.isEmpty(tel)) {
            Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }
        logon();
    }

//   private void logon() {
//        StringRequest stringRequest = new StringRequest(Request.Method.POST, UHBase.login, new Response.Listener<String>() {
//            @Override
//            public void onResponse(String response) {
//                Log.e("UHHomeFragment", response + "....");
//                try {
//                    Gson gson = new Gson();
//                    Dataee dataee = gson.fromJson(response, Dataee.class);
//                    if (dataee.getCode() == "200") {
//                        Toast.makeText(UHLogonActivity.this, dataee.getMsg(), Toast.LENGTH_SHORT).show();
//                        Intent intent = new Intent(UHLogonActivity.this, UHMainActivity.class);
//                        startActivity(intent);
//                        SharedPreUtils.setBoolean(getContext(), "is_Login", true);
//                        SharedPreUtils.setString(getContext(), "user_tel", tel);
//                        SharedPreUtils.setString(getContext(), "user_password", password);
//                        UHLogonActivity.this.finish();
//                    } else if (dataee.getCode() == "413") {
//                        Toast.makeText(UHLogonActivity.this, dataee.getMsg(), Toast.LENGTH_SHORT).show();
//                    }
//                } catch (Exception e) {
//                    Toast.makeText(UHLogonActivity.this, "登陆失败请稍后再试", Toast.LENGTH_SHORT).show();
//                }
//
//            }
//        }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                Log.e("UHHomeFragment", "error:" + error);
//            }
//        }) {
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                //在这里设置需要post的参数
//                Map<String, String> params = new HashMap<String, String>();
//                params.put("telephone", tel);
//                params.put("password", password);
//                return params;
//            }
//        };
//        volleySingleton.addQueue(stringRequest, "logon");
//    }


    private void logon() {
        StringRequest stringRequest = new StringRequest(Request.Method.GET, UHBase.newLogin + "phone=" + tel + "&password=" + password, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    Log.e("RegisteredWoActivity", response);
                    Gson gson = new Gson();
                    StringData dataee = gson.fromJson(response, StringData.class);
                    if (dataee.getCode().equals("0000")) {
//                        dialog_dismiss();
                        Toast.makeText(UHLogonActivity.this, dataee.getMsg(), Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(UHLogonActivity.this, UHMainActivity.class);
                        startActivity(intent);
                        SharedPreUtils.setBoolean(getContext(), "is_Login", true);
                        SharedPreUtils.setString(getContext(), "user_tel", tel);
                        SharedPreUtils.setString(getContext(), "user_password", password);
                        SharedPreUtils.setString(getContext(), "user_token", dataee.getData());
                        UHLogonActivity.this.finish();
                    } else if (dataee.getCode().equals("0105")) {
                        Toast.makeText(UHLogonActivity.this, dataee.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(UHLogonActivity.this, "登陆失败请稍后再试", Toast.LENGTH_SHORT).show();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("UHHomeFragment", "error:" + error);
            }
        }) {
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//                //在这里设置需要post的参数
//                Map<String, String> params = new HashMap<String, String>();
//                params.put("telephone", user_telphone.getText().toString());
//                params.put("password", "123456");
//                return params;
//            }
        };
        volleySingleton.addQueue(stringRequest, "logon");
    }


}
